package com.ssrs.dev.controller;

import com.baomidou.mybatisplus.mapper.EntityWrapper;
import com.baomidou.mybatisplus.plugins.Page;
import com.baomidou.mybatisplus.toolkit.CollectionUtils;
import com.ssrs.core.manager.PageManager;
import com.ssrs.dev.model.Classroom;
import com.ssrs.dev.model.Device;
import com.ssrs.dev.service.IClassroomService;
import com.ssrs.dev.service.IDeviceService;
import com.ssrs.util.commom.APPUtil;
import com.ssrs.util.commom.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;

import java.util.Date;
import java.util.List;

/**
 * <p>
 * 教室设备管理：教室表 前端控制器
 * </p>
 *
 * @author 拾年之璐
 * @since 2021-05-18
 */
@Controller
@RequestMapping("/classroom")
public class ClassroomController {

    @Autowired
    private IClassroomService classroomService;

    @Autowired
    private IDeviceService deviceService;


    /**
     * 接收路由 classroom/index GET 请求
     *
     * @return 跳转到 webapp/WEB-INF/ftl/cxh/classroom/index.ftl 页面
     */
    @RequestMapping(value = "index", method = RequestMethod.GET)
    public String index() {
        return "devPages/classroom/index";
    }


    /**
     * 接收前端 Layui 分页查询请求
     *
     * @param page          当前页
     * @param limit         每页条数（分页大小）
     * @param roomBuildings 是否查询
     * @return 返回查询 JSON 集
     */
    @RequestMapping(value = "getStudentPage", method = RequestMethod.POST)
    @ResponseBody
    public Object getStudentPage(int page, int limit, String roomBuildings, String roomNumber, String RoomAll) {
        if (StringUtils.isNotBlank(RoomAll)) {
            // 简单分页查询.
            Page<Classroom> classroomPage = classroomService.selectPage(
                    // 翻页对象
                    new Page<>(page, limit),
                    // 拼接上like语句【其后还可以继续拼接其他SQL语句，如orderby...】
                    new EntityWrapper<Classroom>().like("is_delete", "0")
                            .like("room_building", RoomAll)
                            .or().like("room_number", RoomAll)
                            .or().like("room_remark", RoomAll)
            );
            // 返回查询JSON结果集合
            return PageManager.buildPage(classroomPage);

        } else {
            boolean isSearch_buildings = false;
            boolean isSearch_number = false;
            // 检索.
            if (StringUtils.isNotBlank(roomBuildings)) {
                isSearch_buildings = true;
            }
            if (StringUtils.isNotBlank(roomNumber)) {
                isSearch_number = true;
            }
            // 简单分页查询.
            Page<Classroom> classroomPage = classroomService.selectPage(
                    // 翻页对象
                    new Page<>(page, limit),
                    // 拼接上like语句【其后还可以继续拼接其他SQL语句，如orderby...】
                    new EntityWrapper<Classroom>().like("is_delete", "0")
                            .like(isSearch_number, "room_number", roomNumber)
                            .like(isSearch_buildings, "room_building", roomBuildings)
            );
            // 返回查询JSON结果集合
            return PageManager.buildPage(classroomPage);
        }
    }


    /**
     * 接收路由 /classroom/goAdd GET 请求
     *
     * @return 跳转到 /webapp/WEB-INF/ftl/cxh/classroom/add.ftl 页面
     */
    @RequestMapping(value = "goAdd", method = RequestMethod.GET)
    public String goAdd() {
        return "devPages/classroom/add";
    }

    /**
     * 接收Ajax /classroom/add POST 请求【加上 @ResponseBody 就代表返回JSON数据，不加 就是返回视图页面】
     *
     * @param classroom ajax提交的信息
     * @return 返回添加成败的JSON提示
     */
    @RequestMapping(value = "add", method = RequestMethod.POST)
    @ResponseBody
    public Object add(Classroom classroom) {
        // 不可添加重复的教室
        List<Classroom> classrooms = classroomService.selectList(
                new EntityWrapper<Classroom>().like("is_delete", "0")
                        .eq("room_building", classroom.getRoomBuilding())
                        .eq("room_number", classroom.getRoomNumber().toString())
        );
        if (!CollectionUtils.isEmpty(classrooms)) {
            return APPUtil.returnMap("4001", "添加失败！该教室已存在！");
        }
        // 为实体添加时间和是否删除状态
        Date date = new Date();
        classroom.setIsDelete(0);
        classroom.setCreateTime(date);
        classroom.setUpdateTime(date);
        // 执行插入并返回结果
        boolean b = classroomService.insert(classroom);
        //如果添加成功，就放回{status:200,message:'添加成功'}的JSON格式类型数据给前台 否则就返回{status:101,message:'添加失败'}
        return b ? APPUtil.resultMapType(APPUtil.INSERT_SUCCESS_TYPE) : APPUtil.resultMapType(APPUtil.INSERT_ERROR_TYPE);
    }


    /**
     * 接收路由 /classroom/goUpdate GET 请求
     *
     * @param id    教室信息的ID（主键）
     * @param model 视图
     * @return 跳转到 /webapp/WEB-INF/ftl/cxh/classroom/update.ftl 页面
     */
    @RequestMapping(value = "goUpdate", method = RequestMethod.GET)
    public String goUpdate(long id, Model model) {
        // 查询当前编辑的教室信息
        Classroom classroom = classroomService.selectById(id);
        //底层原理：使用request.setAttribute()方法
        model.addAttribute("classroom", classroom);
        //返回视图
        return "devPages/classroom/update";
    }

    /**
     * 接收AJAX classroom/update POST 请求
     *
     * @param classroom 编辑后的教室信息
     * @return 编辑成败的JSON
     */
    @RequestMapping(value = "update", method = RequestMethod.POST)
    @ResponseBody
    public Object update(Classroom classroom) {
        // 不可更新为相同的教室
        List<Classroom> classrooms = classroomService.selectList(
                new EntityWrapper<Classroom>().like("is_delete", "0")
                        .eq("room_building", classroom.getRoomBuilding())
                        .eq("room_number", classroom.getRoomNumber().toString())
                        .ne("id", classroom.getId().toString())
        );
        if (!CollectionUtils.isEmpty(classrooms)) {
            return APPUtil.returnMap("4001", "更新失败！不可更新为已存在的教室！");
        }
        Date date = new Date();
        classroom.setUpdateTime(date);
        // 根据 ID 选择修改，只修改不为空的字段
        boolean b = classroomService.updateById(classroom);
        // 返回结果
        return b ? APPUtil.resultMapType(APPUtil.UPDATE_SUCCESS_TYPE) : APPUtil.resultMapType(APPUtil.UPDATE_ERROR_TYPE);
    }

    /**
     * 接收AJAX classroom/del POST 请求
     *
     * @param id 要删除的教室ID
     * @return 删除成败的JSON
     */
    @RequestMapping(value = "del", method = RequestMethod.POST)
    @ResponseBody
    public Object del(int id) {
        // 如果当前教室已经存在设备，不可删除
        List<Device> devices = deviceService.selectList(
                new EntityWrapper<Device>().like("is_delete", "0")
                        .eq("device_classroom", String.valueOf(id))
        );
        if (!CollectionUtils.isEmpty(devices)) {
            return APPUtil.returnMap("4001", "删除失败！该教室存在设备！");
        }

        // 设置删除的数据信息
        Date date = new Date();
        Classroom classroom = new Classroom();
        classroom.setId(id);
        classroom.setIsDelete(1);
        classroom.setDeleteTime(date);
        // 进行逻辑删除
        boolean b = classroomService.updateById(classroom);
        // 返回结果
        return b ? APPUtil.resultMapType(APPUtil.DELEATE_SUCCESS_TYPE) : APPUtil.resultMapType(APPUtil.DELEATE_ERROR_TYPE);
    }

    @RequestMapping(value = "getRoom", method = RequestMethod.GET)
    @ResponseBody
    public Object getClassroom() {
        List<Classroom> classroomList = classroomService.selectList(
                new EntityWrapper<Classroom>().like("is_delete", "0")
        );
        // 返回教室信息列表
        return classroomList;
    }
}

